import axios from "axios";
import { Message, MessageBox } from "element-ui";
import VueCookies from "vue-cookies";
import router from "../project/STmailboxes/router";
import user from "./user";
import configs from "../configs";
import { encrypt } from "./encrypt";

let axiosDefault = axios.create({
  timeout: 30000,
  withCredentials: true,
});

const axiosPublic = {
  async $post(url = "/", data = {}, detaultMsg = "", baseURL = "", other = {}) {
    return await axiosDefault({
      url,
      method: "post",
      headers: { Authorization: user.authorization() },
      data: { data: encrypt(data) },
      baseURL: baseURL || configs.HTTP_URL,
      ...other,
    });
  },

  async $put(url = "/", data = {}, detaultMsg = "", baseURL = "", other = {}) {
    return await axiosDefault({
      url,
      method: "put",
      headers: { Authorization: user.authorization() },
      data: { data: encrypt(data) },
      baseURL: baseURL || configs.HTTP_URL,
      ...other,
    });
  },

  async $get(url = "/", data = {}, detaultMsg = "", baseURL = "", other) {
    return await axiosDefault({
      url,
      method: "get",
      headers: { Authorization: user.authorization() },
      params: data,
      baseURL: baseURL || configs.HTTP_URL,
      ...other,
    });
  },

  async $delete(url = "/", data = {}, detaultMsg = "", baseURL = "", other) {
    return await axiosDefault({
      url,
      method: "delete",
      headers: { Authorization: user.authorization() },
      params: data,
      baseURL: baseURL || configs.HTTP_URL,
      ...other,
    });
  },
};

// 请求拦截
axiosDefault.interceptors.request.use((config) => {
  config.headers.token = user.authorization();
  config.headers.companyId = VueCookies.get("companyId");
  if (configs.PRE) { config.headers.version = configs.PRE_VERSION }
  return config;
});

// 响应拦截
axiosDefault.interceptors.response.use(
  function (response) {
    if (response.data.type == "application/json") {
      handleBlobError(response);
    } else {
      return handleResponseConfig(response);
    }
  },
  function (error) {
    handleResponseErrorConfig(error);
  }
);

// 响应失败处理
function handleResponseErrorConfig(error) {
  const status = error.response.status;
  Message.closeAll();
  const codeMessage = {
    400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
    401: "用户没有权限（令牌、用户名、密码错误）。",
    403: "用户得到授权，但是访问是被禁止的。",
    404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
    406: "请求的格式不可得。",
    410: "请求的资源被永久删除，且不会再得到的。",
    422: "当创建一个对象时，发生一个验证错误。",
    500: "服务器发生错误，请检查服务器。",
    502: "网关错误。",
    503: "服务不可用，服务器暂时过载或维护。",
    504: "网关超时。",
  };
  status ? messageError(codeMessage[status]) : messageError("请求失败！");
}

// 响应成功处理
function handleResponseConfig(response) {
  const code = response.data.code;
  const status = [1001, 1002, 1003, 1008, 1010, 1011, 401, 403];
  if (code && code !== 200) {
    Message.closeAll();
    if (code === 1009) {
      handleCode1009();
    } else if (status.includes(code)) {
      messageError(response.data.msg);
      router.push({ path: "/login" });
    } else {
      messageError(response.data.msg);
    }
  }
  return response.data;
}
// 处理code-1009
function handleCode1009() {
  const alertState = sessionStorage.getItem("alertState");
  if (!alertState) {
    sessionStorage.setItem("alertState", "true");
    MessageBox.alert(
      "您的账号在其他IP地址登录，您被迫退出，若非您本人登录，请修改自己的密码，谨防泄漏。",
      "账号重复登录",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        type: "warning",
      }
    ).then(() => {
      sessionStorage.clear("alertState");
      router.push({ path: "/login" });
    });
  }
}

// 处理blob类型接口失败后blob转json
function handleBlobError(response) {
  const reader = new FileReader();
  reader.readAsText(response.data, "utf-8");
  reader.onload = function () {
    response.data = JSON.parse(reader.result);
    handleResponseConfig(response);
  };
}

// messageError
function messageError(meg) {
  Message({
    message: meg || "请求错误!",
    // center: true,
    type: "error",
  });
}

export default { axiosPublic };
